package com.hanggold.pdf;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;

import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @author <a href="mailto:sunmch@163.com">smc</a>
 * @date 2019-09-18 09:40
 * @since 1.0.0
 **/
public class Pdf2Image {

    private static String PDF_FILE="H:" + File.separator + "yjc.pdf";

    private static String IMAGE_DIR="H:" + File.separator + "pdf2img" + File.separator;

    private static String PDF_FILE_PROP_NAME="pdf.file";

    private static String PDF_TO_IMG_DIR="pdf.image.dir";

    public static void main(String[] args) throws Exception {

        PDF_FILE = System.getProperty(PDF_FILE_PROP_NAME,PDF_FILE);

        IMAGE_DIR = System.getProperty(PDF_TO_IMG_DIR,IMAGE_DIR);

        System.out.printf("pdf文件名称: %s \n",PDF_FILE);

        System.out.printf("pdf生成的图片目录: %s \n",PDF_TO_IMG_DIR);

        long start = System.currentTimeMillis();
        PDDocument document = PDDocument.load(new File(PDF_FILE));
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        int pageCounter = 0;
        for (PDPage page : document.getPages()) {
            // note that the page number parameter is zero based
            BufferedImage bim = pdfRenderer.renderImageWithDPI(pageCounter, 300, ImageType.RGB);
            // suffix in filename will be used as the file format
            ImageIOUtil.writeImage(bim,  IMAGE_DIR+ (pageCounter++) + ".png", 300);
        }
        document.close();
        long end = System.currentTimeMillis();
        System.out.printf("转换pdf花费时间 :  %d", (end - start));



    }
}
